const app = getApp()

Page({
  data: {
    // 通知类型
    notificationTypes: [
      { id: 'all', name: '全部', count: 0 },
      { id: 'order', name: '订单', count: 0 },
      { id: 'system', name: '系统', count: 0 },
      { id: 'activity', name: '活动', count: 0 }
    ],
    
    // 当前选中的类型
    currentType: 'all',
    
    // 通知列表
    notifications: [],
    
    // 页面状态
    loading: false,
    loadingMore: false,
    hasMore: true,
    page: 1,
    pageSize: 20,
    
    // 未读数量
    unreadCount: 0,
    
    // 选择模式
    selectMode: false,
    selectedIds: [],
    
    // 筛选和排序
    showFilter: false,
    filterOptions: {
      status: 'all', // all: 全部, read: 已读, unread: 未读
      timeRange: 'all' // all: 全部, today: 今天, week: 本周, month: 本月
    }
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    // 刷新通知数据
    this.loadNotifications(true)
  },

  onPullDownRefresh() {
    this.loadNotifications(true)
    wx.stopPullDownRefresh()
  },

  onReachBottom() {
    this.loadMore()
  },

  // 初始化页面
  async initPage() {
    wx.setNavigationBarTitle({
      title: '消息通知'
    })
    
    await this.loadNotifications(true)
  },

  // 加载通知数据
  async loadNotifications(refresh = false) {
    if (this.data.loading) return
    
    this.setData({
      loading: refresh,
      page: refresh ? 1 : this.data.page
    })
    
    try {
      const result = await this.fetchNotifications(
        this.data.currentType,
        this.data.page,
        this.data.filterOptions
      )
      
      const notifications = refresh ? result.notifications : [
        ...this.data.notifications,
        ...result.notifications
      ]
      
      this.setData({
        notifications,
        hasMore: result.hasMore,
        unreadCount: result.unreadCount,
        notificationTypes: this.updateTypeCounts(result.typeCounts)
      })
      
    } catch (error) {
      console.error('加载通知失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({
        loading: false
      })
    }
  },

  // 获取通知数据
  async fetchNotifications(type, page, filters) {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockNotifications = this.generateMockNotifications(type, page, filters)
        resolve({
          notifications: mockNotifications,
          hasMore: page < 3,
          unreadCount: 5,
          typeCounts: {
            all: 25,
            order: 12,
            system: 8,
            activity: 5
          }
        })
      }, 1000)
    })
  },

  // 生成模拟通知数据
  generateMockNotifications(type, page, filters) {
    const notifications = []
    const types = ['order', 'system', 'activity']
    
    for (let i = 0; i < this.data.pageSize; i++) {
      const notificationType = type === 'all' ? 
        types[Math.floor(Math.random() * types.length)] : type
      
      const notification = {
        id: `${page}_${i}`,
        type: notificationType,
        title: this.getNotificationTitle(notificationType),
        content: this.getNotificationContent(notificationType),
        time: this.getRandomTime(),
        isRead: Math.random() > 0.3,
        avatar: this.getNotificationAvatar(notificationType),
        actionType: this.getActionType(notificationType),
        actionData: this.getActionData(notificationType)
      }
      
      notifications.push(notification)
    }
    
    return notifications
  },

  // 获取通知标题
  getNotificationTitle(type) {
    const titles = {
      order: ['订单已确认', '配送中', '订单已完成', '订单已取消', '退款成功'],
      system: ['系统维护通知', '版本更新', '服务条款更新', '隐私政策更新', '账户安全提醒'],
      activity: ['新用户专享优惠', '限时抢购', '满减活动', '积分兑换', '会员特权']
    }
    
    const typeList = titles[type] || titles.system
    return typeList[Math.floor(Math.random() * typeList.length)]
  },

  // 获取通知内容
  getNotificationContent(type) {
    const contents = {
      order: [
        '您的订单已被商家确认，正在准备中...',
        '您的订单正在配送中，预计20分钟送达',
        '您的订单已送达，感谢您的使用',
        '很抱歉，您的订单已被取消',
        '您的退款已处理完成，请查收'
      ],
      system: [
        '系统将于今晚2:00-4:00进行维护',
        '新版本已发布，快来体验新功能',
        '我们更新了服务条款，请查看',
        '隐私政策已更新，保护您的权益',
        '检测到异常登录，请注意账户安全'
      ],
      activity: [
        '新用户专享8.8折优惠券已到账',
        '限时抢购活动开始，数量有限',
        '满50减10活动火热进行中',
        '积分商城上新，快来兑换好礼',
        '会员专享免配送费特权'
      ]
    }
    
    const typeList = contents[type] || contents.system
    return typeList[Math.floor(Math.random() * typeList.length)]
  },

  // 获取随机时间
  getRandomTime() {
    const now = new Date()
    const randomHours = Math.floor(Math.random() * 72) // 3天内
    const time = new Date(now.getTime() - randomHours * 60 * 60 * 1000)
    
    const diff = now.getTime() - time.getTime()
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const minutes = Math.floor(diff / (1000 * 60))
    
    if (minutes < 60) {
      return `${minutes}分钟前`
    } else if (hours < 24) {
      return `${hours}小时前`
    } else {
      const days = Math.floor(hours / 24)
      return `${days}天前`
    }
  },

  // 获取通知头像
  getNotificationAvatar(type) {
    const avatars = {
      order: '/images/notification/order.png',
      system: '/images/notification/system.png',
      activity: '/images/notification/activity.png'
    }
    return avatars[type] || avatars.system
  },

  // 获取操作类型
  getActionType(type) {
    const actions = {
      order: 'order_detail',
      system: 'web_view',
      activity: 'activity_detail'
    }
    return actions[type] || 'none'
  },

  // 获取操作数据
  getActionData(type) {
    const data = {
      order: { orderId: Math.floor(Math.random() * 10000) },
      system: { url: 'https://example.com/help' },
      activity: { activityId: Math.floor(Math.random() * 100) }
    }
    return data[type] || {}
  },

  // 更新类型计数
  updateTypeCounts(counts) {
    return this.data.notificationTypes.map(type => ({
      ...type,
      count: counts[type.id] || 0
    }))
  },

  // 切换通知类型
  switchType(e) {
    const type = e.currentTarget.dataset.type
    
    if (type === this.data.currentType) return
    
    this.setData({
      currentType: type,
      notifications: [],
      page: 1,
      hasMore: true
    })
    
    this.loadNotifications(true)
  },

  // 点击通知项
  onNotificationTap(e) {
    const { index } = e.currentTarget.dataset
    const notification = this.data.notifications[index]
    
    // 标记为已读
    if (!notification.isRead) {
      this.markAsRead([notification.id])
    }
    
    // 执行相应操作
    this.handleNotificationAction(notification)
  },

  // 处理通知操作
  handleNotificationAction(notification) {
    switch (notification.actionType) {
      case 'order_detail':
        wx.navigateTo({
          url: `/pages/order-detail/order-detail?id=${notification.actionData.orderId}`
        })
        break
      case 'activity_detail':
        wx.navigateTo({
          url: `/pages/activity/activity?id=${notification.actionData.activityId}`
        })
        break
      case 'web_view':
        wx.navigateTo({
          url: `/pages/webview/webview?url=${encodeURIComponent(notification.actionData.url)}`
        })
        break
      default:
        // 显示详情
        this.showNotificationDetail(notification)
    }
  },

  // 显示通知详情
  showNotificationDetail(notification) {
    wx.showModal({
      title: notification.title,
      content: notification.content,
      showCancel: false
    })
  },

  // 标记为已读
  async markAsRead(ids) {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 更新本地数据
      const notifications = this.data.notifications.map(item => ({
        ...item,
        isRead: ids.includes(item.id) ? true : item.isRead
      }))
      
      const unreadCount = notifications.filter(item => !item.isRead).length
      
      this.setData({
        notifications,
        unreadCount
      })
      
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  },

  // 全部标记为已读
  markAllAsRead() {
    const unreadIds = this.data.notifications
      .filter(item => !item.isRead)
      .map(item => item.id)
    
    if (unreadIds.length === 0) {
      wx.showToast({
        title: '没有未读消息',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认操作',
      content: `确定要将${unreadIds.length}条消息标记为已读吗？`,
      success: (res) => {
        if (res.confirm) {
          this.markAsRead(unreadIds)
        }
      }
    })
  },

  // 切换选择模式
  toggleSelectMode() {
    this.setData({
      selectMode: !this.data.selectMode,
      selectedIds: []
    })
  },

  // 选择/取消选择通知
  toggleSelect(e) {
    const { id } = e.currentTarget.dataset
    const selectedIds = [...this.data.selectedIds]
    const index = selectedIds.indexOf(id)
    
    if (index > -1) {
      selectedIds.splice(index, 1)
    } else {
      selectedIds.push(id)
    }
    
    this.setData({
      selectedIds
    })
  },

  // 全选/取消全选
  toggleSelectAll() {
    const allIds = this.data.notifications.map(item => item.id)
    const isAllSelected = this.data.selectedIds.length === allIds.length
    
    this.setData({
      selectedIds: isAllSelected ? [] : allIds
    })
  },

  // 批量删除
  batchDelete() {
    if (this.data.selectedIds.length === 0) {
      wx.showToast({
        title: '请选择要删除的消息',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除${this.data.selectedIds.length}条消息吗？`,
      success: (res) => {
        if (res.confirm) {
          this.deleteNotifications(this.data.selectedIds)
        }
      }
    })
  },

  // 删除通知
  async deleteNotifications(ids) {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 更新本地数据
      const notifications = this.data.notifications.filter(
        item => !ids.includes(item.id)
      )
      
      this.setData({
        notifications,
        selectedIds: [],
        selectMode: false
      })
      
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      })
      
    } catch (error) {
      console.error('删除失败:', error)
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      })
    }
  },

  // 显示筛选
  showFilter() {
    this.setData({
      showFilter: true
    })
  },

  // 隐藏筛选
  hideFilter() {
    this.setData({
      showFilter: false
    })
  },

  // 应用筛选
  applyFilter(e) {
    const { status, timeRange } = e.detail
    
    this.setData({
      filterOptions: { status, timeRange },
      showFilter: false,
      notifications: [],
      page: 1,
      hasMore: true
    })
    
    this.loadNotifications(true)
  },

  // 加载更多
  loadMore() {
    if (this.data.loadingMore || !this.data.hasMore) return
    
    this.setData({
      loadingMore: true,
      page: this.data.page + 1
    })
    
    this.loadNotifications(false).finally(() => {
      this.setData({
        loadingMore: false
      })
    })
  },

  // 清空所有通知
  clearAll() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有通知吗？此操作不可恢复',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            notifications: [],
            unreadCount: 0,
            selectedIds: [],
            selectMode: false
          })
          
          wx.showToast({
            title: '已清空',
            icon: 'success'
          })
        }
      }
    })
  }
}) 